/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-07
*/
package com.rzico.basics.controller.admin;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Supplier;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.SupplierService;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.basics.entity.Promotion;
import com.rzico.basics.service.PromotionService;
import com.rzico.basics.entity.PromotionGift;
import com.rzico.basics.service.PromotionGiftService;
import com.rzico.basics.entity.Qrcode;
import com.rzico.basics.service.QrcodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.components.barcode4j.QRCodeImageProducer;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 促销活动控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-07
 */
@Api(description = "促销活动接口")
@RestController
@RequestMapping("/admin/promotion")
public class PromotionAdminController extends BaseController {

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private  PromotionGiftService promotionGiftService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页查询促销活动
     *
     * @return
    */
    @ApiOperation("分页查询促销活动")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "促销方式 {0:新人礼包,1:消费后送,2.扫码领券,3.满减,4.满折,5.满赠,6.满包邮,7.买送,8.秒杀,9.第二件半价,10.新人价}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "promotionType", value = "促销类型(0.全场活动,1.单品活动)", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "productCategoryId", value = "商品分类（单品活动专用）", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0.待审核，1.已审核，2.已过期）", dataType = "Integer", paramType = "query")
    })
    public CommResult<Promotion> list(Date startDate, Date endDate,Integer type,Integer promotionType,Long productCategoryId,Integer status, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate", startDate);
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (type!=null){
            params.put("type", type);
        }

        if (promotionType!=null){
            params.put("promotionType", promotionType);
        }

        if (productCategoryId!=null) {
            params.put("treePath",String.valueOf(productCategoryId));
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }
        params.put("deleted", false);

        if (status!=null){
            params.put("status", status);
        }

        //检查是否供应商账号
        if (promotionType!=null && promotionType==1) {
            SysUser sysUser = sysUserService.getCurrent();
            Supplier supplier = supplierService.findByUserId(sysUser.getId());
            if (supplier != null) {
                params.put("supplierId", supplier.getId());
            }
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Promotion> list = promotionService.selectList(params);
        PageResult<Promotion> pageResult = new PageResult<Promotion>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条促销活动
     *
     * @return
    */
    @ApiOperation("查询单条促销活动")
    @GetMapping("/find/{id}")
    public CommResult<Promotion> find(@PathVariable String id) {
        Promotion result = promotionService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("promotion",result);
        return CommResult.success(data);

    }

    /**
     * 保存促销活动
     *
     * @param promotion
     * @return
     */
    @ApiOperation("保存促销活动")
    @PostMapping("/save")
    public CommResult<Promotion> save(@RequestBody Promotion promotion) {

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise==null) {
            return CommResult.error("没有开通企业");
        }
        promotion.setCreateDate(new Date());
        promotion.setEnterpriseId(enterprise.getId());

        if (promotion.getType().equals(7) || promotion.getType().equals(8) || promotion.getType().equals(9) || promotion.getType().equals(10)) {
            if (promotion.getGoodsId()==null) {
                return CommResult.error("请选择促销商品");
            }


        }

        if (promotion.getType().equals(7)) {
            if (promotion.getMinimumPrice().compareTo(BigDecimal.ZERO)<=0) {
                return CommResult.error("买送数量不能为0");
            }
            if (promotion.getAmount().compareTo(BigDecimal.ZERO)<=0) {
                return CommResult.error("买送数量不能为0");
            }
        }

        if (promotion.getStatus()==null) {
            promotion.setStatus(0);
        }
        if (promotion.getStock()==null) {
            promotion.setStock(0);
        }
        if (promotion.getAgioRate()==null) {
            promotion.setAgioRate(BigDecimal.ZERO);
        }
        if (promotion.getAmount()==null) {
            promotion.setAmount(BigDecimal.ZERO);
        }
        if (promotion.getType().equals(2)) {
            promotion.setFirsted(false);
        }

        promotionService.save(promotion);
        Promotion result = promotionService.findById(promotion.getId());
        return CommResult.success(result);

    }

    /**
     * 批量删除促销活动
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除促销活动", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除促销活动,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Promotion> del(@PathVariable String ids) {

        promotionService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新促销活动
     *
     * @param promotion
     * @return
     */
    @Log(desc = "更新促销活动", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新促销活动")
    @PostMapping("/update")
    public CommResult<Promotion> update(@RequestBody Promotion promotion) {

        if (promotion.getType().equals(7) || promotion.getType().equals(8) || promotion.getType().equals(9) || promotion.getType().equals(10)) {
            if (promotion.getGoodsId()==null) {
                return CommResult.error("请选择促销商品");
            }
        }

        if (promotion.getType().equals(7)) {
            if (promotion.getMinimumPrice().compareTo(BigDecimal.ZERO)<=0) {
                return CommResult.error("买送数量不能为0");
            }
            if (promotion.getAmount().compareTo(BigDecimal.ZERO)<=0) {
                return CommResult.error("买送数量不能为0");
            }
        }

        if (promotion.getStatus()==null) {
            promotion.setStatus(0);
        }
        if (promotion.getType().equals(2)) {
            promotion.setFirsted(false);
        }
        promotionService.update(promotion);
        Promotion result = promotionService.findById(promotion.getId());
        return CommResult.success(result);
    }

    /**
     * 审核状态更新
     *
     * @param promotion
     * @return
     */

    @Log(desc = "审核状态更新", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("审核状态更新")
    @PostMapping("/updatePromotion")
    public CommResult<Promotion> updatePromotion(@RequestBody Promotion promotion) {
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise==null) {
            return CommResult.error("没有开通企业");
        }

        promotionService.updatePromotion(promotion);
        Promotion result = promotionService.findById(promotion.getId());
        return CommResult.success(result);
    }

}
